package com.sophie.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @Author: Rowena
 * @CreateTime: 2024-08-28 16:21:46
 * @Version: 1.0
 */

public class BaseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //在doGet方法中调用doPost,这样doPost就可以集中处理所有请求
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1.从请求参数中获取method对应的数据
        request.setCharacterEncoding("utf-8");
        String methodName = request.getParameter("method");

        //2.通过反射调用method方法
        Class<? extends BaseServlet> clazz = this.getClass();
        System.out.println("正在调用--->" + clazz.getName()+"的" + methodName+"方法!");

        try {
            //获取方法
            // 参数1:方法名
            // 参数2:方法中的参数列表的数据类型
            Method method = clazz.getDeclaredMethod
                    (methodName, HttpServletRequest.class, HttpServletResponse.class);
            //设置访问权限
            method.setAccessible(true);
            //调用
            method.invoke(this,request,response);
        } catch (Exception e) {
            System.out.println("^_^请你好好检查一下调用的方法名!");
            e.printStackTrace();
        }

    }
}
